<?php
// 如：db:seed 或者 清空数据库命令的地方调用


function is_request_from_api()
{
    return $_SERVER['SERVER_NAME'] == env('API_DOMAIN');
}


/**
 * 判断是否处于微信内置浏览器中
 *
 * @return boolean
 */
function in_weixin()
{
    $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);

    if (preg_match('/micromessenger/i', $user_agent)) {
        return true;
    }

    return false;
}


/**
 * 判断是否处于微信电脑版内置浏览器中
 *
 * @return boolean
 */
function in_windows_weixin()
{
    $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);

    if (preg_match('/windowswechat/i', $user_agent)) {
        return true;
    }

    return false;
}


function curlRequest($url, $postData = array(), $launch = 'post', $contentType = 'text/html')
{
    $result = "";
    try {
        $header = array("Content-Type:" . $contentType . ";charset=utf-8");
        if (!empty($_SERVER['HTTP_USER_AGENT'])) {        //是否有user_agent信息
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
        }
        $cur = curl_init();
        curl_setopt($cur, CURLOPT_URL, $url);
        curl_setopt($cur, CURLOPT_HEADER, 0);
        curl_setopt($cur, CURLOPT_HTTPHEADER, $header);
        curl_setopt($cur, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($cur, CURLOPT_TIMEOUT, 30);
        //https
        curl_setopt($cur, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($cur, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (isset($user_agent)) {
            curl_setopt($cur, CURLOPT_USERAGENT, $user_agent);
        }
        curl_setopt($cur, CURLOPT_ENCODING, 'gzip');
        if (is_array($postData)) {
            if ($postData && count($postData) > 0) {
                $params = http_build_query($postData);
                if ($launch == 'get') {        //发送方式选择
                    curl_setopt($cur, CURLOPT_HTTPGET, $params);
                } else {
                    curl_setopt($cur, CURLOPT_POST, true);
                    curl_setopt($cur, CURLOPT_POSTFIELDS, $params);
                }
            }
        } else {
            if (!empty($postData)) {
                $params = $postData;
                if ($launch == 'post') {
                    curl_setopt($cur, CURLOPT_POST, true);
                    curl_setopt($cur, CURLOPT_POSTFIELDS, $params);
                }
            }
        }
        $result = curl_exec($cur);
        curl_close($cur);
    } catch (Exception $e) {

    }
    return $result;
}


/**
 * 递归创建目录
 *
 * 与 mkdir 不同之处在于支持一次性多级创建, 比如 /dir/sub/dir/
 *
 * @param  string
 * @param  int
 * @return boolean
 */
function make_dir($dir, $permission = 0777)
{
    $dir = rtrim($dir, '/') . '/';

    if (is_dir($dir)) {
        return TRUE;
    }

    if (!make_dir(dirname($dir), $permission)) {
        return FALSE;
    }

    return @mkdir($dir, $permission);
}


/**
 * 标准化的api输出json格式
 * @param $errorCode Integer  错误码
 * @param array|string $data 数据
 * @param $msg string 输出信息
 * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
 *
 */
function apiJson($errorCode, $data, $msg)
{
    $content = [
        'errcode' => $errorCode,
        'msg' => $msg,
        'data' => $data
    ];
    return response($content);
}

/**
 * api成功返回函数
 * @param $data array 数据
 * @return array
 */
function apiSuccess($data = null)
{
    return apiJson(config('errorcode.success.code'), $data, config('errorcode.success.msg'));
}

/**
 * api失败返回函数
 * @param $data array 数据
 * @return array
 */
function apiFailed($data = null,$msg = null)
{
    return apiJson(config('errorcode.fail.code'), $data, $msg ? $msg : config('errorcode.fail.msg'));
}

function apiErrcode($codeKey){
    return apiJson(config("errorcode.$codeKey.code"), null, config("errorcode.$codeKey.msg"));
}

/**
 * api的错误返回函数
 * @param $data array 数据
 * @return array
 */
function apiError($data = null)
{
    return apiJson(config('errorcode.error.code'), $data, config('errorcode.error.msg'));
}

function barCodeFailed($data = null,$msg = null)
{
    return apiJson(config('errorcode.bar_code_error.code'), $data, $msg?$msg:config('errorcode.bar_code_error.msg'));
}


/**
 * 获取缓存的key的完整结构
 * @param $key
 * @return string
 */
function getCacheKey($key)
{
    return config('testing.run_model') . config($key);
}

function getAppBasePath(){
    return str_replace('\\','/',realpath(dirname(__FILE__).'/../'))."/";
}

function getBasePath(){
    return str_replace('\\','/',realpath(dirname(__FILE__).'/../../'))."/";
}


function formateFormula($formula){
   $array = explode(',',$formula);
    $operator = [];
    $parameter = [];
    foreach($array as $k=>$v){
        if($k%2 !== 0){
            array_push($operator,$v);
        }else{
            array_push($parameter,$v);
        }
    }
    $data = array('operator'=>$operator,'parameter'=>$parameter);
    return $data;
}


function redirectToUrl($url){
    header("Location:".$url);
}


/**
 * CURL 获取文件内容
 *
 * 用法同 file_get_contents
 *
 * @param string
 * @param integerr
 * @return string
 */
function curl_get_contents($url, $timeout = 10)
{
    if (!function_exists('curl_init'))
    {
        throw new Zend_Exception('CURL not support');
    }

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_HEADER, FALSE);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36');


    if (substr($url, 0, 8) == 'https://')
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
    }

    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}

/*
 * 获取用户IP的函数
 */
function getIp(){
    $onlineip = "";
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $onlineip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $onlineip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $onlineip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $onlineip = $_SERVER['REMOTE_ADDR'];
    }
    return $onlineip;
}

/**是否为https请求
 * @return bool
 */
function is_https()
{
    if (!isset($_SERVER['HTTPS']))
        return FALSE;
    if ($_SERVER['HTTPS'] === 1) {  //Apache
        return TRUE;
    } elseif ($_SERVER['HTTPS'] === 'on') { //IIS
        return TRUE;
    } elseif ($_SERVER['SERVER_PORT'] == 443) { //其他
        return TRUE;
    }
    return FALSE;
}

/**
 * 格式化数组的数据
 * @param $arr
 * @param $key
 * @param string $default
 * @return mixed
 */
function formatArrValue($arr, $key, $default = ""){
    return isset($arr[$key]) ? $arr[$key] : $default;
}

/**
 * 格式化数组的数据
 * @param $text
 * @param $arr
 * @return mixed
 * @throws \App\Exceptions\UserException
 */
function my_sprintf($text, $arr){
    $len = count($arr);
    if ($len == 0) {
        return $text;
    } elseif ($len == 1) {
        return sprintf($text, $arr[0]);
    } elseif ($len == 2) {
        return sprintf($text, $arr[0], $arr[1]);
    } elseif ($len == 3) {
        return sprintf($text, $arr[0], $arr[1], $arr[2]);
    } elseif ($len == 4) {
        return sprintf($text, $arr[0], $arr[1], $arr[2], $arr[3]);
    } elseif ($len == 5) {
        return sprintf($text, $arr[0], $arr[1], $arr[2], $arr[3], $arr[4]);
    } elseif ($len == 6) {
        return sprintf($text, $arr[0], $arr[1], $arr[2], $arr[3], $arr[4], $arr[5]);
    }
    throw new \App\Exceptions\UserException("解析的数组长度过长");
}










